package com.objectdraw.client.objectdraw;
import java.awt.*;
import java.awt.event.MouseEvent;

/**
 * controls mouse events for selecting objects
 * @author jgulik, cfruehan
 *
 */
public class SelectTool implements Tool{
	DrawingCanvas canvas;
	IDrawingObject selected;
	IDrawingObjectLink selectedLink;
	Point lastPoint;
	
	/**
	 * instantiates the tool
	 * @param canvas the canvas upon which the tool acts
	 */
	public SelectTool(DrawingCanvas d){
		canvas=d;
	}
	
	/**
	 * if an object is selected the anchor point is moved to follow the moving mouse
	 */
	public void mouseDragged(MouseEvent e) {
		if(canvas.magicBox.active){
			Point thisPoint=e.getPoint();
			selected.moveAnchor(thisPoint.x-lastPoint.x, thisPoint.y-lastPoint.y);
			canvas.magicBox.moveAnchor(thisPoint.x-lastPoint.x, thisPoint.y-lastPoint.y);
			lastPoint=thisPoint;
		}
		canvas.repaint();
	}
	

	/**
	 * Checks if the point in the mouseevent is within the bounding box of an object. If so it 
	 * moves that object to the top of the list of objects and surrounded with a magic box.
	 * 
	 */
	public void mousePressed(MouseEvent e) {
		// selection action!
		IDrawingObjectLink current = canvas.firstObject;
		IDrawingObjectLink prev = null;
		canvas.magicBox.active=false;
		lastPoint=e.getPoint();
		while(current!=null){
			if(current.o.isPointInObject(lastPoint)){
				selected=current.o;
				selectedLink=current;
				//Color saveColor = canvas.getImageBufferGraphics().getColor( );
				canvas.magicBox.active=true;
				canvas.magicBox.p1=new Point(current.o.getLeft()-2,current.o.getTop()-2);
				canvas.magicBox.p2=new Point(current.o.getLeft()+current.o.getWidth()+2,current.o.getTop()+current.o.getHeight()+2);
				break;
			}
			prev=current;
			current=current.next;
		}
		//bring selected objects to the top
		if(canvas.magicBox.active && prev!=null){
			//take current out
			prev.next=current.next;
			if(current.next!=null){
				current.next.prev=prev;
			}else{//special case: current was the last object
				canvas.lastObject=prev;
			}
			current.prev=null;
			//put it on top
			canvas.push(current);
		}
		canvas.repaint();
	}

	/**
	 * move the anchor point of the selected object to and repaint
	 */
	public void mouseReleased(MouseEvent e) {
		if(canvas.magicBox.active){
			Point thisPoint=e.getPoint();
			selected.moveAnchor(thisPoint.x-lastPoint.x, thisPoint.y-lastPoint.y);
			canvas.magicBox.moveAnchor(thisPoint.x-lastPoint.x, thisPoint.y-lastPoint.y);
		}
		canvas.repaint();
	}
	
//	public void mouseMoved(MouseEvent e){
//		//highlight action!
//		IDrawingObjectLink current = canvas.firstObject;
//		while(current!=null){
//			if(current.o.isPointInObject(e.getPoint())){
//				canvas.getImageBufferGraphics().drawRect(current.o.getLeft()-2, current.o.getTop()-2, current.o.getWidth()+4, current.o.getHeight()+4);
//				break;
//			}
//			current=current.next;
//		}
//	}

}
